package com.myqf.d4_线程同步.作业;

import lombok.Data;
import lombok.SneakyThrows;

/*
采用Java 多线程技术，设计实现一个符合生产者和消费者问题的程序。对一个对象（枪膛）进行操作，其最大容量是12颗子弹。
生产者线程是一个压入线程，它不断向枪膛中压入子弹；消费者线程是一个射出线程，它不断从枪膛中射出子弹。
 */
public class 模拟生产者消费者模式 {
    public static void main(String[] args) {
        Bore bore = new Bore();

        new Thread(new User(bore),"用户").start();
        new Thread(new Yield(bore),"商家").start();
    }
}

@Data
class Bore{
    private int num = 0;
    void add() {
        num+=12;
        System.out.println(Thread.currentThread().getName()+"子弹安装完毕  当前子弹为"+num);
    }
    void del() {
        num=0;
        System.out.println(Thread.currentThread().getName()+"子弹sheji完毕  当前子弹为"+num);
    }
}

class Yield implements Runnable{
    private Bore bore;
    public Yield(Bore bore) {
        this.bore=bore;
    }
    @SneakyThrows
    @Override
    public void run() {
        synchronized (bore) {
            while (true) {
                if (bore.getNum() == 0) {
                    bore.add();
                    bore.notify();
                    bore.wait();
                }

            }
        }
    }
}

class User implements Runnable{
    private Bore bore;
    public User(Bore bore) {
        this.bore = bore;
    }
    @SneakyThrows
    @Override
    public void run() {
        synchronized (bore) {
            while (true) {
                bore.wait();
                    bore.del();
                    bore.notify();
                Thread.sleep(500);
            }
        }
    }
}